<template>
  <view class="container">
    <!-- 加载状态 -->
    <view v-if="loading" class="loading">加载中...</view>

    <!-- 错误提示 -->
    <view v-if="error" class="error" @click="retry">{{ error }}（点击重试）</view>

    <!-- 商品列表 -->
    <scroll-view v-show="!loading && !error" scroll-y style="height: 100vh; padding: 20rpx;">
      <view class="sku-list">
        <view v-for="(item, index) in skuList" :key="item.skuId" class="sku-card">
          <image :src="item.skuImage" mode="aspectFill" class="sku-image" />
          <view class="sku-details">
            <!-- 使用 white-space 和 word-break 来控制文本换行 -->
            <text class="name">{{ item.skuName }}</text>
            <text class="info-field">价格：￥{{ item.price / 100 }}/天</text>
            <text class="info-field">单位：{{ item.unit }}</text>
            <text class="info-field">品牌：{{ item.brandName }}</text>
          </view>
        </view>
      </view>
    </scroll-view>

  </view>
</template>

<script>
import { listSku } from '@/api/sku'

export default {
  data() {
    return {
      loading: false,
      error: null,
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      skuList: []
    }
  },
  onLoad() {
    this.getList()
  },
  methods: {
    getList() {
      this.loading = true
      this.error = null

      listSku(this.queryParams)
        .then(res => {
          if (res.code === 200) {
            // 注意这里 res.data 不存在，直接是 res.rows
            this.skuList = res.rows || []
          } else {
            this.error = '获取商品列表失败'
            this.skuList = []
          }
        })
        .catch(err => {
          console.error('请求异常:', err)
          this.error = '网络异常，请检查连接'
          this.skuList = []
        })
        .finally(() => {
          this.loading = false
        })
    },
    retry() {
      if (!this.loading) {
        this.getList()
      }
    }
  }
}
</script>

<style scoped>
.sku-list {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.sku-card {
  display: flex;
  background-color: #fff;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  padding: 20rpx;
}

.sku-image {
  width: 180rpx;
  height: 180rpx;
  border-radius: 12rpx;
  margin-right: 20rpx;
}

.sku-details {
  flex: 1;
  display: flex;
  flex-direction: column;
}

/* 控制文本字段样式 */
.info-field {
  margin-top: 10rpx;
  white-space: pre-wrap; /* 保留空白符序列，但是正常地进行换行 */
  word-break: break-all; /* 在任意字符间断行 */
}

.name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
}
</style>